// 1.创建网站服务器，实现客户端与服务器端的通信
// 2.连接数据库，创建用户集合，向集合中插入文档
// 3. 当用户访问/list时，将所有用户信息查询出来
  // 3.(1) 实现路由功能
  // 3.(2) 呈现用户列表页面
  // 3.(3) 从数据库中查询用户信息，将用户信息展示在列表中
  // 3.(4) 将用户信息和表格HTML进行拼接并将拼接结果响应回客户端
// 4. 当用户访问/add时，呈现表单页面，并实现添加用户信息功能
// 5. 当用户访问/modify时，呈现修改页面，并实现修改用户信息功能
// 6. 当用户访问/remove时，实现用户删除功能

const http = require('http');
const app = http.createServer();



const url = require('url');
// 解析post参数变成对象形式
const queryString = require('querystring');

// 引入模块文件
require('./model/index.js');
const User = require('./model/user');


app.on('request', async (req, res) => {
    
    res.writeHead(200, {
        'content-type': 'text/html; charset=utf8'
    });

    let method = req.method;
    let {pathname, query} = url.parse(req.url, true);

    if (method == 'GET') {
        if (pathname == '/list') {

            // 获取User下面的所有文档
            let users = await User.find();

            
            // 进行拼接
            let list = `<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>用户列表</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
            </head>
            <body>
                <div class="container">
                    <h6>
                        <a href="add" class="btn btn-primary">添加用户</a>
                    </h6>
                    <table class="table table-striped table-bordered">
                        <tr>
                            <td>用户名</td>
                            <td>年龄</td>
                            <td>爱好</td>
                            <td>邮箱</td>
                            <td>操作</td>
                        </tr>`;
            users.forEach(item => {
                list += `
                <tr>
				    <td>${item.name}</td>
				    <td>${item.age}</td>
				    <td>`
                item.hobbies.forEach(item => {
                    list += `
                    <span>${item}</span>`
                })
                list += `
                    </td>
				    <td>${item.email}</td>
				    <td>
				    	<a href="/remove?id=${item._id}" class="btn btn-danger btn-xs">删除</a>
				    	<a href="/modify?id=${item._id}" class="btn btn-success btn-xs">修改</a>
				    </td>
			    </tr>`
            })
            list += `</table>

	</div>
</body>
</html>`


            // 输出拼接内容
            res.end(list);
        } else if (pathname == '/add') {
            let add = `
            <!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>用户列表</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
	<div class="container">
		<h3>添加用户</h3>
		<form method="POST" action="/add">
		  <div class="form-group">
		    <label>用户名</label>
		    <input type="text" class="form-control" placeholder="请填写用户名" name="name">
		  </div>
		  <div class="form-group">
		    <label>密码</label>
		    <input type="password" class="form-control" placeholder="请输入密码" name="password">
		  </div>
		  <div class="form-group">
		    <label>年龄</label>
		    <input type="text" class="form-control" placeholder="请填写年龄" name="age">
		  </div>
		  <div class="form-group">
		    <label>邮箱</label>
		    <input type="email" class="form-control" placeholder="请填写邮箱" name="email">
		  </div>
		  <div class="form-group">
		    <label>请选择爱好</label>
            <div>
                <label class="checkbox-inline">
		    	  <input type="checkbox" value="吃饭" name="hobbies"> 吃饭
		    	</label>
                <label class="checkbox-inline">
		    	  <input type="checkbox" value="睡觉" name="hobbies"> 睡觉
		    	</label>
                <label class="checkbox-inline">
		    	  <input type="checkbox" value="打豆豆" name="hobbies"> 打豆豆
		    	</label>
		    	<label class="checkbox-inline">
		    	  <input type="checkbox" value="足球" name="hobbies"> 足球
		    	</label>
		    	<label class="checkbox-inline">
		    	  <input type="checkbox" value="篮球" name="hobbies"> 篮球
		    	</label>
		    	<label class="checkbox-inline">
		    	  <input type="checkbox" value="橄榄球" name="hobbies"> 橄榄球
		    	</label>
		    	<label class="checkbox-inline">
		    	  <input type="checkbox" value="敲代码" name="hobbies"> 敲代码
		    	</label>
		    	<label class="checkbox-inline">
		    	  <input type="checkbox" value="抽烟" name="hobbies"> 抽烟
		    	</label>
		    	<label class="checkbox-inline">
		    	  <input type="checkbox" value="喝酒" name="hobbies"> 喝酒
		    	</label>
		    	<label class="checkbox-inline">
		    	  <input type="checkbox" value="烫头" name="hobbies"> 烫头
		    	</label>
		    </div>
		  </div>
		  <button type="submit" class="btn btn-primary">添加用户</button>
		</form>
	</div>
</body>
</html>
            `;
            res.end(add);
        } else if (pathname == '/modify') {
            // 先在数据库找到对应id的文档
            let users = await User.findOne({_id: query.id});
            // console.log(users);
            let hobbies = ['吃饭', '睡觉', '打豆豆', '足球', '篮球', '橄榄球', '敲代码', '抽烟', '喝酒', '烫头'];
            let add = `
            <!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>用户列表</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
	<div class="container">
		<h3>修改用户</h3>
		<form method="POST" action="/modify?id=${users._id}">
		  <div class="form-group">
		    <label>用户名</label>
		    <input type="text" class="form-control" value="${users.name}" placeholder="请填写用户名" name="name">
		  </div>
		  <div class="form-group">
		    <label>密码</label>
		    <input type="password" class="form-control" value="${users.password}" placeholder="请输入密码" name="password">
		  </div>
		  <div class="form-group">
		    <label>年龄</label>
		    <input type="text" class="form-control" value="${users.age}" placeholder="请填写年龄" name="age">
		  </div>
		  <div class="form-group">
		    <label>邮箱</label>
		    <input type="email" class="form-control" value="${users.email}" placeholder="请填写邮箱" name="email">
		  </div>
		  <div class="form-group">
		    <label>请选择爱好</label>
		    <div>`;
                
            // <label class="checkbox-inline">
		    // 	  <input type="checkbox" value="足球" name="hobbies"> 足球
		    // 	</label>

            hobbies.forEach(item => {
                if (users.hobbies.includes(item)) {
                    add += `
                    <label class="checkbox-inline">
		    	        <input type="checkbox" value="${item}" name="hobbies" checked > ${item}
                    </label>`;
                } else {
                    add += `
                    <label class="checkbox-inline">
		    	        <input type="checkbox" value="${item}" name="hobbies" > ${item}
                    </label>`;
                };
            });

            
		    add += `
            </div>
		  </div>
		  <button type="submit" class="btn btn-primary">完成修改</button>
		</form>
	</div>
</body>
</html>`;
            // console.log(query);
            res.end(add);
        } else if (pathname == '/remove') {
            await User.findOneAndDelete({_id: query.id});
            res.writeHead(301, {
                Location: '/list'
            });
            res.end();
        }
    } else if (method == 'POST') {
        if (pathname == '/add') {
            // 接收post参数
            let formData = ``;
            req.on('data', (params) => {
                formData += params;
            })
            // 接收post参数结束
            req.on('end', async () => {
                let users = queryString.parse(formData);
                // 将post参数对象传入数据库
                await User.create(users);
                res.writeHead(301, {
                    Location: `/list`
                });
                res.end('操');
            })
        } else if (pathname == '/modify') {
            // 接收post参数
            let formData = ``;
            req.on('data', (params) => {
                formData += params;
            })
            // 接收post参数结束
            req.on('end', async () => {
                let users = queryString.parse(formData);
                // 将post参数对象传入数据库
                await User.updateOne({_id: query.id}, users);
                res.writeHead(301, {
                    Location: `/list`
                });
                res.end('操');
            })
        }
    }
    // res.end('ok')
})

// 监听端口
app.listen(80);
console.log('网站服务器启动成功');